using System;
using System.Collections.Generic;
using System.ServiceProcess;

namespace Catastrophe.Common.WindowsApi
{
	public class WinService
	{
		public static bool IsServiceExist(string serviceName)
		{
			bool result = false;
			ServiceController[] services = ServiceController.GetServices();
			try
			{
				ServiceController[] array = services;
				foreach (ServiceController serviceController in array)
				{
					if (serviceController.ServiceName.ToUpper() == serviceName.ToUpper())
					{
						result = true;
						break;
					}
				}
			}
			catch (Exception)
			{
				result = false;
			}
			return result;
		}

		public static bool IsServiceStarted(string serviceName)
		{
			ServiceController serviceController = new ServiceController();
			serviceController.ServiceName = serviceName;
			return serviceController.Status == ServiceControllerStatus.Running;
		}

		public static bool StartService(string serviceName, bool waitiStatus = true)
		{
			ServiceController serviceController = new ServiceController();
			serviceController.ServiceName = serviceName;
			if (serviceController.Status == ServiceControllerStatus.Running || serviceController.Status == ServiceControllerStatus.StartPending)
			{
				return true;
			}
			try
			{
				serviceController.Start();
				if (waitiStatus)
				{
					serviceController.WaitForStatus(ServiceControllerStatus.Running);
				}
				return true;
			}
			catch (InvalidOperationException)
			{
				return false;
			}
		}

		public static List<string> GetServices()
		{
			List<string> list = new List<string>();
			ServiceController[] services = ServiceController.GetServices();
			ServiceController[] array = services;
			foreach (ServiceController serviceController in array)
			{
				list.Add($"ServiceName:{serviceController.ServiceName}|ServiceStatus:{serviceController.Status}");
			}
			return list;
		}

		public static bool StopService(string serviceName, bool waitiStatus = true)
		{
			ServiceController serviceController = new ServiceController();
			serviceController.ServiceName = serviceName;
			if (serviceController.Status == ServiceControllerStatus.Stopped || serviceController.Status == ServiceControllerStatus.StopPending)
			{
				return true;
			}
			try
			{
				serviceController.Stop();
				if (waitiStatus)
				{
					serviceController.WaitForStatus(ServiceControllerStatus.Stopped);
				}
				return true;
			}
			catch (InvalidOperationException)
			{
				return false;
			}
		}
	}
}
